package com.socialsoftware.Page;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.MenuBuilder;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.socialsoftware.MediaCommunication.service.CallService;
import com.socialsoftware.MediaCommunication.service.WebSocketService;
import com.socialsoftware.MediaCommunication.utils.Constants;
import com.socialsoftware.R;
import com.socialsoftware.databinding.ActivityMainBinding;
import com.socialsoftware.util.SessionManager;

import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private ActivityMainBinding binding;
    private PopupWindow popupWindow;
    private BottomNavigationView navView;
    private static final int QR_SCAN_REQUEST_CODE = 101;
    private SessionManager sessionManager;

    // 来电广播接收器
    private final BroadcastReceiver incomingCallReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.ACTION_INCOMING_CALL.equals(intent.getAction())) {
                String caller = intent.getStringExtra(Constants.EXTRA_CALLER_NAME);
                String mode = intent.getStringExtra(Constants.EXTRA_CALL_MODE);
                Log.d(TAG, "收到来电: " + caller + ", 通话模式: " + mode);
                
                // 启动来电界面
                Intent incomingCallIntent = new Intent(MainActivity.this, 
                    com.socialsoftware.MediaCommunication.activity.IncomingCallActivity.class);
                incomingCallIntent.putExtra(Constants.EXTRA_CALLER_NAME, caller);
                incomingCallIntent.putExtra(Constants.EXTRA_CALL_MODE, mode);
                incomingCallIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(incomingCallIntent);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        
        // 获取会话管理器
        sessionManager = SessionManager.getInstance(this);
        
        // 确保服务已启动
        checkAndStartCommunicationServices();

        // 确保正确处理系统UI
        setupSystemUI();

        // Set up bottom navigation
        navView = findViewById(R.id.nav_view);
        
        // 确保导航栏高度正确
        fixBottomNavigationHeight();
        
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(binding.navView, navController);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 注册广播接收器
        IntentFilter filter = new IntentFilter(Constants.ACTION_INCOMING_CALL);
        LocalBroadcastManager.getInstance(this).registerReceiver(incomingCallReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 取消注册广播接收器
        LocalBroadcastManager.getInstance(this).unregisterReceiver(incomingCallReceiver);
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == com.socialsoftware.util.PermissionUtils.PERMISSION_REQUEST_CODE) {
            boolean allPermissionsGranted = true;
            
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }
            
            if (allPermissionsGranted && sessionManager != null && sessionManager.isLoggedIn()) {
                // 所有权限已获得，启动通话服务
                String username = sessionManager.getUser().getUsername();
                if (username != null && !username.isEmpty()) {
                    startCallService(username);
                }
            } else {
                // 权限被拒绝，可以显示提示或禁用相关功能
                Toast.makeText(this, "通话功能需要麦克风权限才能正常工作", Toast.LENGTH_LONG).show();
            }
        }
    }

    // 检查并启动通信服务
    private void checkAndStartCommunicationServices() {
        if (sessionManager != null && sessionManager.isLoggedIn() && sessionManager.getUser() != null) {
            String username = sessionManager.getUser().getUsername();
            if (username != null && !username.isEmpty()) {
                Log.d(TAG, "检查并启动通信服务，用户名: " + username);
                
                // 启动WebSocket服务
                Intent webSocketServiceIntent = new Intent(this, WebSocketService.class);
                webSocketServiceIntent.putExtra("username", username);
                startService(webSocketServiceIntent);
                
                // 检查权限并启动通话服务
                checkPermissionsAndStartCallService(username);
            }
        }
    }
    
    // 检查所需权限并启动通话服务
    private void checkPermissionsAndStartCallService(String username) {
        // 获取所需权限数组
        String[] permissions = com.socialsoftware.util.PermissionUtils.getCallServicePermissions();
        
        // 检查是否已授予所有权限
        if (com.socialsoftware.util.PermissionUtils.hasPermissions(this, permissions)) {
            // 已获得所有权限，启动服务
            startCallService(username);
        } else {
            // 请求缺少的权限
            com.socialsoftware.util.PermissionUtils.requestPermissions(
                    this, 
                    permissions,
                    com.socialsoftware.util.PermissionUtils.PERMISSION_REQUEST_CODE
            );
            // 权限请求结果会在 onRequestPermissionsResult 中处理
        }
    }
    
    // 启动通话服务
    private void startCallService(String username) {
        Intent callServiceIntent = new Intent(this, CallService.class);
        callServiceIntent.putExtra("username", username);
        startService(callServiceIntent);
    }
    
    private void fixBottomNavigationHeight() {
        // 等待视图完全绘制后再获取高度
        navView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 移除监听器，避免重复调用
                navView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                
                // 确保导航栏高度正确
                int navViewHeight = navView.getMeasuredHeight();
                if (navViewHeight > 0) {
                    ViewGroup.LayoutParams layoutParams = navView.getLayoutParams();
                    layoutParams.height = navViewHeight;
                    navView.setLayoutParams(layoutParams);
                    
                    // 强制重新布局
                    binding.getRoot().requestLayout();
                }
            }
        });
    }
    
    private void setupSystemUI() {
        // 确保内容不会被系统UI遮挡
        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
        
        // 设置状态栏颜色
        getWindow().setStatusBarColor(getResources().getColor(R.color.purple_700));
        
        // 设置导航栏颜色
        getWindow().setNavigationBarColor(getResources().getColor(android.R.color.white));
        
        // 设置内容边距，避免被系统UI遮挡
        ViewCompat.setOnApplyWindowInsetsListener(binding.getRoot(), (v, insets) -> {
            int statusBarHeight = insets.getInsets(WindowInsetsCompat.Type.statusBars()).top;
            int navigationBarHeight = insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom;
            
            // 调整内容区域的边距
            View navHostFragment = findViewById(R.id.nav_host_fragment_activity_main);
            navHostFragment.setPadding(
                    navHostFragment.getPaddingLeft(),
                    statusBarHeight,
                    navHostFragment.getPaddingRight(),
                    navHostFragment.getPaddingBottom()
            );
            
            return insets;
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.top_app_bar, menu);
        
        // Show icons in overflow menu (optional)
        if (menu instanceof MenuBuilder) {
            try {
                Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                method.setAccessible(true);
                method.invoke(menu, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_search) {
            // Handle search action
            Toast.makeText(this, "搜索功能", Toast.LENGTH_SHORT).show();
            return true;
        } else if (id == R.id.action_add) {
            // Show custom popup menu for add options
            showCustomAddMenu();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void showCustomAddMenu() {
        // Inflate the popup layout
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View popupView = inflater.inflate(R.layout.popup_add_menu, null);

        // Create the popup window
        popupWindow = new PopupWindow(
                popupView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );

        // Set background to make the popup dismissable when clicking outside
        popupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        popupWindow.setElevation(10);
        
        // Set animation style
        popupWindow.setAnimationStyle(R.style.PopupMenuAnimation);

        // Set up click listeners for the popup items
        LinearLayout layoutStartGroupChat = popupView.findViewById(R.id.layout_start_group_chat);
        LinearLayout layoutAddFriend = popupView.findViewById(R.id.layout_add_friend);
        LinearLayout layoutScanQR = popupView.findViewById(R.id.layout_scan_qr);

        layoutStartGroupChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "发起群聊", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
        });

        layoutAddFriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 打开添加好友页面
                Intent intent = new Intent(MainActivity.this, AddFriendActivity.class);
                startActivity(intent);
                popupWindow.dismiss();
            }
        });

        layoutScanQR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Launch QR scanner activity
                Intent intent = new Intent(MainActivity.this, QRScannerActivity.class);
                startActivityForResult(intent, QR_SCAN_REQUEST_CODE);
                popupWindow.dismiss();
            }
        });

        // Calculate the position to show the popup
        int yOffset = getSupportActionBar().getHeight() + getStatusBarHeight();
        
        // Show the popup window at the right top corner of the app
        popupWindow.showAtLocation(findViewById(android.R.id.content), Gravity.TOP | Gravity.END, 10, yOffset);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == QR_SCAN_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            String scanResult = data.getStringExtra("SCAN_RESULT");
            if (scanResult != null && !scanResult.isEmpty()) {
                // Handle the QR code scan result
                handleQRScanResult(scanResult);
            }
        }
    }
    
    private void handleQRScanResult(String result) {
        // Process the QR code result
        // This could be a user ID, a group invitation, or a URL
        Toast.makeText(this, "扫描结果: " + result, Toast.LENGTH_LONG).show();
        
        // Example: Check if it's a user profile
        if (result.startsWith("user:")) {
            String userId = result.substring(5); // Remove "user:" prefix
            // Open user profile or add friend
            // Intent userIntent = new Intent(this, FriendProfileActivity.class);
            // userIntent.putExtra("USER_ID", userId);
            // startActivity(userIntent);
        } 
        // Add more handlers for different QR code formats as needed
    }
    
    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}